﻿using System;
using System.Web.Security;
using System.Windows.Forms;
using HRM.HRMServiceProxy;
using HRM.Properties;
using HRM.Controller;
using System.Net;


namespace HRM
{
    public partial class frmLogin : FormBase
    {
        DialogResult _retVal;
        //frmSplash Splasher;
        public frmLogin()
        {
            InitializeComponent();
            //
            Init_Control();
        }

        public override void Show_Form()
        {
            Show();
        }

        protected override void Init_Control()
        {
            FormGlobals.Control_SetRequired(txtUser, txtPassword);
            FormGlobals.TextBox_SetWaterMark("Tên đăng nhập", 2, txtUser);
            FormGlobals.TextBox_SetWaterMark("Mật khẩu", 2, txtPassword);
            
            //SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            //BackColor = Color.FromArgb(66, 66, 66);
            //TransparencyKey = Color.FromArgb(66, 66, 66);
            //
            txtUser.Text = Properties.Settings.Default.LastUser;
            _retVal = DialogResult.Cancel;
            //
            btnLogin.FlatStyle = FlatStyle.Flat;
            btnLogin.FlatAppearance.BorderSize = 0;
            //btnLogin.FlatAppearance.BorderColor = Color.FromArgb(0, 255, 255, 255); //Transparent
            //btnLogin.BackColor = Color.FromArgb(0, 1, 191, 254);
            //
            //txtPassword.Focus();
            FirstFocusControl = txtPassword;
        }

        void LoadLanguage()
        {
            if (this.Tag != null)
                this.Text = UpdateUI.GetString(this.Tag.ToString());
            //UpdateUI.Load_Panel(ref panel1);
            //UpdateUI.Load_Panel(ref panel2);
        }
        //Kiểm tra đăng nhập
        private bool CheckLogin()
        {
            var logged = true;
            try
            {
                UserInfo userInf = null;
                
                FormGlobals.App_ProgressShow(delegate()
                {
                    if (txtUser.Text.Trim().Length == 0)
                    {
                        MessageBox.Show(UpdateUI.GetString("tendangnhapkhongdetrong"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        logged = false;
                    }
                    if (txtPassword.Text.Trim().Length == 0)
                    {
                        MessageBox.Show(UpdateUI.GetString("matkhaukhongdetrong"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        logged = false;
                    }
                    Program.strUserName = txtUser.Text.ToUpper().Trim();
                    Program.strPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text.Trim(), "SHA1");

                    var wcfUser = Service.User();
                    userInf = wcfUser.User_GetUserInfo(txtUser.Text);
                }, "Kiểm tra đăng nhập...");

                if (userInf == null)
                {
                    MessageBox.Show(HrmResources.USERNAME_OR_PASS_INVALID, HrmResources.NOTIFY, MessageBoxButtons.OK);
                    logged = false;
                }
                else if (txtPassword.Text != userInf.PassWord)
                {

                    MessageBox.Show(HrmResources.USERNAME_OR_PASS_INVALID, HrmResources.NOTIFY, MessageBoxButtons.OK);
                    txtPassword.SetFocus_SelectAll();
                    logged = false;
                }

                if (logged)
                {
                    FormGlobals.App_ProgressShow(delegate()
                    {
                        //Từ phiên bản 1.0.5.56 trở đi, có thêm config Remote
                        //Gán địa chỉ mới
                        //if (String.IsNullOrEmpty(Globals.Application_GetConfig("RemoteConnect")))
                        //{
                            var sServiceAdd = Settings.Default.ServiceAddress;
                            //Lưu vào App.Config, sử dụng DAL
                            string sLoginConnect = sServiceAdd.Substring(0, sServiceAdd.LastIndexOf('/'));
                            
                            //Đòi quyền đọc ghi file config
                            //Globals.Application_SetConfig("RemoteConnect", sLoginConnect);
                            //Globals.Application_SetConfig("LoginConnect", "net." + sLoginConnect);
                            //Globals.Application_SetConfig("WorkingConnect", "net." + sLoginConnect);
                        //}
                        //
                        Settings.Default.LastUser = txtUser.Text;
                        Settings.Default.Save();

                        if (userInf != null)
                        {
                            UIParamater.FullNameOfUser = userInf.FullName;
                            Program.intBranchID = userInf.BranchID == "" ? 0 : Convert.ToInt32(userInf.BranchID);
                        }
                        
                        //Save Log
                        string strHostName = Dns.GetHostName();
                        IPAddress[] addr = Dns.GetHostAddresses(strHostName);
                        string IPAdd = "";
                        for (int i = 0; i < addr.Length; i++)
                        {
                            if (i == 0)
                                IPAdd = addr[i].ToString();
                            else
                                IPAdd += "; " + addr[i].ToString();
                        }
                        string sComputer = "Version: " + Program.Version + "; ComputerName: " + strHostName.ToUpper() + "; PrivateIP: " + IPAdd;
                        HeThong_Controller.Instance().SaveLog(txtUser.Text, sComputer);

                        //
                        ProxyConfig.ReNewAddress();
                        //
                        Service.LoadSystem();
                        //Service.LoadEmployeeQuantity();
                        Service.LoadRoleRight();
                        var wcfEmployee = Service.Employee();
                        LocalDB.dtTableEmployee = wcfEmployee.Employee_GetAllWithBranch(Program.intBranchID).Tables[0];
                    }, "Khởi tạo chương trình...");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            return logged;
        }


        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (!FormGlobals.Panel_CheckError(pnlInput))
                return;
            if (CheckLogin())
            {
                _retVal = DialogResult.OK;
                Close();

                //Nếu là mật khẩu mặc định, mở form yêu cầu đổi pass
                string sDefaultPass = Properties.Settings.Default.DefaultPass;
                if (txtPassword.Text.Trim() == sDefaultPass)
                {
                    frmChangePassword frm = new frmChangePassword(true);
                    frm.ShowDialog();
                }
                //
            }
        }

        private void frmLogin_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult = _retVal;
        }

        private void frmLogin_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    if (!e.Alt && !e.Control)
                    {
                        ProcessTabKey(!e.Shift);
                        e.Handled = true;
                    }
                    break;
                case Keys.Escape:
                    Close();
                    break;
            }
        }
        //
        private void lnkCauHinh_Click(object sender, EventArgs e)
        {
            var f = new frmConfig();
            if (f.ShowDialog(this) == DialogResult.OK)
            {
                _retVal = DialogResult.OK;
                Close();
            }
        }

        private void lnkThoat_Click(object sender, EventArgs e)
        {
            if (!FormGlobals.Message_Confirm("Bạn có chắc chắn muốn thoát khỏi chương trình"))
                return;
            //
            Close();
        }

        private void frmLogin_Load(object sender, EventArgs e)
        {
            txtPassword.Focus();
        }
    }
}